package com.lagou.sqlsession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SimpleExecutor
 * @Description:
 * @Author: qiaojiacheng
 * @Date: 2021/7/22 4:50 下午
 */
public class SimpleExecutor implements Executor {


    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mapperStatement, params);
        // 5. 执行sql，获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6. 封装结果集
        Class<?> resultType = mapperStatement.getResultType();

        List<E> list = new ArrayList<>();
        while (resultSet.next()) {
            Object o = resultType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取属性名
                String columnName = metaData.getColumnName(i);
                // 获取属性值
                Object value = resultSet.getObject(columnName);
                // 使用反射或内省，根据数据库表和和实体的对应关系，完成封装
                // 创建属性描述器，为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                // 获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                // 像类中写入值
                writeMethod.invoke(o, value);
            }
            list.add((E) o);
        }

        return list;
    }

    @Override
    public int update(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mapperStatement, params);
        int executeUpdate = preparedStatement.executeUpdate();
        return executeUpdate;
    }

    /**
     * 获取 PreparedStatement
     *
     * @param
     * @return
     * @author qiaojiacheng
     * @date 2021/7/29 4:28 下午
     */
    private PreparedStatement getPreparedStatement(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 1. 注册驱动获取连接
        Connection connection = configuration.getDataSource().getConnection();
        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mapperStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        String sqlText = boundSql.getSqlText();
        // 3. 获取预编译对象：prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(sqlText);
        //获取传入参数类型
        Class<?> parameterType = mapperStatement.getParameterType();
        // 4. 设置参数
        // 设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            Field declaredField = parameterType.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            // 参数的值
            Object o = declaredField.get(params[0]);
            // 给占位符赋值
            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

    private BoundSql getBoundSql(String sql) {
        // 标记处理类，主要是通过配合GenericTokenParser类完成对配置文件等的解析
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // GenericTokenParser:通用的标记解析器，完成了代码片段中的占位符解析，然后再根据给定的标记处理器（TokenHandler—）来进行表达式的处理
        // 三个参数：分别openToken（开始标记），closeToken（结束标记），handler（标记处理器）
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
